<template>
  <div class="document-preview-container">
    <!-- 头部工具栏 -->
    <div class="preview-header">
      <div class="header-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/knowledge' }">知识管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/knowledge/space/${spaceId}` }">
            {{ spaceName }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ documentInfo?.documentName || '文档' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button :type="viewMode === 'preview' ? 'primary' : ''" @click="viewMode = 'preview'">
            <el-icon>
              <View />
            </el-icon>
            预览
          </el-button>
          <el-button :type="viewMode === 'source' ? 'primary' : ''" @click="viewMode = 'source'">
            <el-icon>
              <Document />
            </el-icon>
            源码
          </el-button>
        </el-button-group>
        <el-divider direction="vertical" />
        <el-button @click="downloadDocument">
          <el-icon>
            <Download />
          </el-icon>
          下载
        </el-button>
        <el-button @click="editDocument" :disabled="!canEdit" :title="canEditTooltip">
          <el-icon>
            <Edit />
          </el-icon>
          编辑
        </el-button>
        <el-button @click="toggleFullscreen">
          <el-icon>
            <FullScreen />
          </el-icon>
          全屏
        </el-button>
        <el-button @click="closePreview">
          <el-icon>
            <Close />
          </el-icon>
          关闭
        </el-button>
      </div>
    </div>

    <!-- 文档信息栏 -->
    <div class="document-info-bar" v-if="documentInfo && documentInfo.documentId">
      <div class="info-left">
        <div class="doc-title">
          <el-icon class="title-icon">
            <Document />
          </el-icon>
          <h2>{{ documentInfo?.documentName || '未知文档' }}</h2>
          <el-tag :type="getTypeTagType(documentInfo?.documentType)" size="small">
            {{ getTypeLabel(documentInfo?.documentType) }}
          </el-tag>
        </div>
        <div class="doc-meta">
          <span class="meta-item">
            <el-icon>
              <User />
            </el-icon>
            创建者: {{ documentInfo?.creatorUsername || '未知' }}
          </span>
          <span class="meta-item">
            <el-icon>
              <Calendar />
            </el-icon>
            创建时间: {{ formatDate(documentInfo?.createdAt) }}
          </span>
          <span class="meta-item">
            <el-icon>
              <EditPen />
            </el-icon>
            最后编辑: {{ formatDate(documentInfo?.updatedAt) }}
          </span>
          <span class="meta-item">
            <el-icon>
              <View />
            </el-icon>
            版本: v{{ documentInfo?.version || '1' }}
          </span>
        </div>
      </div>
      <div class="info-right">
        <el-button size="small" @click="toggleFavorite">
          <el-icon>
            <Star />
          </el-icon>
          {{ isFavorite ? '取消收藏' : '收藏' }}
        </el-button>
        <el-button size="small" @click="showVersionHistoryDialog">
          <el-icon>
            <Clock />
          </el-icon>
          版本历史
        </el-button>

      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="preview-content" :class="{ 'fullscreen': isFullscreen }">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <el-result icon="error" title="加载失败" :sub-title="error">
          <template #extra>
            <el-button type="primary" @click="loadDocument">重新加载</el-button>
          </template>
        </el-result>
      </div>

      <!-- 预览模式 -->
      <div v-else-if="viewMode === 'preview'" class="preview-mode">
        <!-- Markdown 预览 -->
        <div v-if="documentInfo?.documentType === 'markdown'" class="markdown-preview">
          <div id="vditor-preview" class="vditor-preview"></div>
        </div>

        <!-- 文本预览 -->
        <div v-else-if="documentInfo?.documentType === 'text' || documentInfo?.fileExtension === 'txt'"
          class="text-preview">
          <div id="vditor-text-preview" class="vditor-preview"></div>
        </div>

        <!-- Word文档预览 -->
        <div
          v-else-if="documentInfo?.fileExtension === 'docx' || documentInfo?.documentType === 'word' || documentInfo?.documentType === 'docx'"
          class="word-preview">
          <div v-if="wordHtmlContent" class="word-content" v-html="wordHtmlContent"></div>
          <div v-else class="loading-word">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>
            <span>正在转换Word文档...</span>
          </div>
        </div>

        <!-- PDF文档预览 -->
        <div v-else-if="documentInfo?.fileExtension === 'pdf' || documentInfo?.documentType === 'pdf'"
          class="pdf-preview">
          <iframe v-if="pdfUrl" :src="pdfUrl" class="pdf-iframe" frameborder="0"></iframe>
          <div v-else class="loading-pdf">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>
            <span>正在加载PDF文档...</span>
          </div>
        </div>

        <!-- 其他文件类型 -->
        <div v-else class="file-preview">
          <el-result icon="info" title="暂不支持预览此文件类型">
            <template #extra>
              <el-button type="primary" @click="downloadDocument">下载查看</el-button>
            </template>
          </el-result>
        </div>
      </div>

      <!-- 源码模式 -->
      <div v-else class="source-mode">
        <div class="source-header">
          <span class="file-info">{{ documentInfo?.documentName || '未知文档' }} ({{ documentInfo?.fileSize || 0 }}
            字节)</span>
          <el-button size="small" @click="copySource">
            <el-icon>
              <CopyDocument />
            </el-icon>
            复制源码
          </el-button>
        </div>
        <pre class="source-content"><code>{{ documentContent }}</code></pre>
      </div>
    </div>

    <!-- 目录侧边栏 -->
    <div class="toc-sidebar" v-if="showToc && tocItems.length > 0">
      <div class="toc-header">
        <h4>目录</h4>
        <el-button size="small" text @click="showToc = false">
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </div>
      <div class="toc-content">
        <div v-for="item in tocItems" :key="item.id" :class="['toc-item', `toc-level-${item.level}`]"
          @click="scrollToHeading(item.id)">
          {{ item.text }}
        </div>
      </div>
    </div>

    <!-- 版本历史对话框 -->
    <el-dialog v-model="showVersionHistory" title="版本历史" width="800px">
      <div class="version-history">
        <el-timeline>
          <el-timeline-item v-for="version in versionHistory" :key="version.versionId"
            :timestamp="formatDate(version.createdAt)" placement="top">
            <div class="version-item">
              <div class="version-header">
                <span class="version-number">v{{ version.versionNumber }}</span>
                <span class="version-author">{{ version.editorUsername }}</span>
                <div class="version-actions">
                  <el-button size="small" @click="previewVersion(version)">
                    预览
                  </el-button>
                  <el-button size="small" @click="restoreVersion(version)">
                    恢复
                  </el-button>
                </div>
              </div>
              <div class="version-summary">{{ version.editSummary || '无编辑说明' }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { documentApi, knowledgeSpaceApi } from '@/api/knowledge'
import { useUserStore } from '@/stores/user'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import mammoth from 'mammoth'
import {
  View, Document, Download, Edit, FullScreen, Close, Star, Clock,
  User, Calendar, EditPen, Loading, CopyDocument
} from '@element-plus/icons-vue'

export default {
  name: 'DocumentPreview',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()

    // 获取当前登录用户信息
    const getCurrentUser = () => {
      try {
        const userInfo = JSON.parse(localStorage.getItem('system-user') || '{}')
        console.log('获取到的用户信息:', userInfo)
        // 优先使用name字段，如果没有则使用username字段
        const username = userInfo?.name || userInfo?.username
        console.log('提取的用户名:', username)
        if (username && username.trim() !== '') {
          return username.trim()
        }
        console.warn('用户信息不完整或为空:', userInfo)
        return null
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return null
      }
    }

    // 响应式数据
    const documentInfo = ref({})
    const documentContent = ref('')
    const markdownHtml = ref('')
    const wordHtmlContent = ref('')
    const pdfUrl = ref('')
    const tocItems = ref([])
    const versionHistory = ref([])
    const loading = ref(true)
    const error = ref('')
    const viewMode = ref('preview') // preview, source
    const isFullscreen = ref(false)
    const showToc = ref(false)
    const showVersionHistory = ref(false)
    const isFavorite = ref(false)

    // 计算属性
    const spaceId = computed(() => route.params.spaceId)
    const documentId = computed(() => route.params.documentId)
    const spaceName = computed(() => documentInfo.value?.spaceName || '未知空间')

    // 判断是否可以编辑
    const canEdit = computed(() => {
      const docType = documentInfo.value?.documentType?.toLowerCase()
      const fileExt = documentInfo.value?.fileExtension?.toLowerCase()
      return docType === 'markdown' || docType === 'text' || fileExt === 'md' || fileExt === 'txt'
    })

    // 编辑按钮提示文本
    const canEditTooltip = computed(() => {
      if (canEdit.value) {
        return '编辑文档'
      } else {
        const docType = documentInfo.value?.documentType?.toLowerCase()
        const fileExt = documentInfo.value?.fileExtension?.toLowerCase()
        if (docType === 'pdf' || fileExt === 'pdf') {
          return 'PDF格式文档无法编辑'
        } else if (docType === 'docx' || docType === 'word' || fileExt === 'docx') {
          return 'Word格式文档无法编辑'
        } else {
          return '此格式文档无法编辑'
        }
      }
    })

    // 方法
    const loadDocument = async () => {
      loading.value = true
      error.value = ''

      try {
        // 验证documentId参数
        if (!documentId.value) {
          throw new Error('文档ID参数缺失')
        }

        const parsedDocumentId = parseInt(documentId.value)
        if (isNaN(parsedDocumentId)) {
          throw new Error('文档ID参数格式无效: ' + documentId.value)
        }

        console.log('准备加载文档，documentId:', parsedDocumentId)

        // 检查是否来自最近访问或收藏功能
        const fromRecentOrFavorite = route.query.from === 'recent' || route.query.from === 'favorite'

        // 获取当前用户名
        const currentUser = getCurrentUser()
        if (!currentUser) {
          throw new Error('无法获取当前用户信息，请重新登录')
        }

        // 加载文档信息
        const docResponse = await documentApi.getDocumentById(
          parsedDocumentId,
          currentUser,
          fromRecentOrFavorite
        )

        console.log('API响应:', docResponse)

        if (!docResponse) {
          throw new Error('API响应为空')
        }

        // 检查API响应状态
        if (docResponse.code && docResponse.code !== 200 && docResponse.code !== '200') {
          console.error('API响应错误:', docResponse)
          throw new Error(docResponse.msg || docResponse.message || '获取文档失败')
        }

        if (!docResponse.data) {
          console.error('API响应结构:', docResponse)
          throw new Error(`API响应数据为空，响应码: ${docResponse.code || '未知'}, 消息: ${docResponse.message || '无消息'}`)
        }

        documentInfo.value = docResponse.data

        console.log('文档信息:', documentInfo.value)

        // 获取空间信息以显示正确的空间名称
        if (documentInfo.value.spaceId) {
          try {
            const spaceResponse = await knowledgeSpaceApi.getSpaceById(
              documentInfo.value.spaceId,
              currentUser
            )
            if (spaceResponse && spaceResponse.data) {
              documentInfo.value.spaceName = spaceResponse.data.spaceName
            }
          } catch (spaceError) {
            console.warn('获取空间信息失败:', spaceError)
          }
        }

        // 根据文档类型处理内容
        const docType = documentInfo.value?.documentType?.toLowerCase()
        const fileExt = documentInfo.value?.fileExtension?.toLowerCase()
        console.log('文档类型判断 - docType:', docType, 'fileExt:', fileExt)

        if (docType === 'markdown' || fileExt === 'md') {
          // Markdown文档：直接使用文档内容
          documentContent.value = documentInfo.value.content || ''
          console.log('Markdown内容:', documentContent.value)

          // 初始化Vditor预览
          await nextTick()
          initVditorPreview()
        } else if (docType === 'text' || fileExt === 'txt') {
          // 文本文档：直接使用文档内容
          documentContent.value = documentInfo.value.content || ''
          console.log('文本内容:', documentContent.value)

          // 初始化Vditor文本预览
          await nextTick()
          initVditorTextPreview()
        } else if (docType === 'docx' || docType === 'word' || fileExt === 'docx') {
          // Word文档：使用Mammoth.js转换
          console.log('检测到Word文档，docType:', docType, 'fileExt:', fileExt)
          await loadWordDocument()
        } else if (docType === 'pdf' || fileExt === 'pdf') {
          // PDF文档：使用iframe预览
          await loadPdfDocument()
        } else {
          // 其他类型直接获取内容
          documentContent.value = documentInfo.value.content || ''
        }

        // 检查是否已收藏
        checkFavoriteStatus()

      } catch (err) {
        console.error('加载文档失败:', err)

        // 特殊处理权限错误 - 暂时禁用权限控制
        // if (err.message && err.message.includes('没有访问该文档的权限')) {
        //   error.value = '您没有访问该文档的权限。可能的原因：\n1. 您不是该知识空间的成员\n2. 该文档所在的空间是私有空间\n3. 您的权限已被撤销\n\n请联系空间管理员申请访问权限。'
        // } else {
        error.value = err.message || '加载文档失败'
        // }
      } finally {
        loading.value = false
      }
    }

    const checkFavoriteStatus = async () => {
      try {
        const currentUser = getCurrentUser()
        if (!currentUser) {
          console.warn('无法获取当前用户信息，跳过检查收藏状态')
          return
        }
        const response = await documentApi.getFavoriteDocuments(currentUser)
        if (response.code === '200') {
          isFavorite.value = response.data.some(doc => doc.documentId === parseInt(documentId.value))
        } else {
          console.error('检查收藏状态失败:', response.msg)
        }
      } catch (error) {
        console.error('检查收藏状态失败:', error)
      }
    }

    const toggleFavorite = async () => {
      try {
        const currentUser = getCurrentUser()
        if (!currentUser) {
          ElMessage.error('无法获取当前用户信息，请重新登录')
          return
        }

        if (isFavorite.value) {
          await documentApi.removeFromFavorites(documentId.value, currentUser)
          ElMessage.success('已取消收藏')
        } else {
          await documentApi.addToFavorites(documentId.value, currentUser)
          ElMessage.success('已添加到收藏')
        }
        isFavorite.value = !isFavorite.value
      } catch (error) {
        ElMessage.error('操作失败: ' + error.message)
      }
    }

    const downloadDocument = async () => {
      try {
        // 创建下载链接
        let content = ''
        let fileName = ''
        let mimeType = ''

        const docType = documentInfo.value?.documentType?.toLowerCase()
        const fileExt = documentInfo.value?.fileExtension?.toLowerCase()

        if (docType === 'markdown' || fileExt === 'md') {
          // 对于markdown文档，下载其内容
          content = documentContent.value || ''
          fileName = `${documentInfo.value?.documentName || 'document'}.md`
          mimeType = 'text/plain;charset=utf-8'
        } else if (docType === 'text' || fileExt === 'txt') {
          // 对于text文档，下载其内容
          content = documentContent.value || ''
          fileName = `${documentInfo.value?.documentName || 'document'}.txt`
          mimeType = 'text/plain;charset=utf-8'
        } else {
          // 对于其他类型的文档（docx, pdf等），提示用户
          ElMessage.info(`文档 "${documentInfo.value?.documentName || '未知文档'}" 是${docType || fileExt || '未知'}格式，请联系管理员获取原始文件`)
          return
        }

        // 创建Blob对象
        const blob = new Blob([content], { type: mimeType })
        const url = window.URL.createObjectURL(blob)

        // 创建下载链接
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()

        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success(`文档 "${documentInfo.value?.documentName || '未知文档'}" 下载成功`)
      } catch (error) {
        console.error('下载文档失败:', error)
        ElMessage.error('下载文档失败，请稍后重试')
      }
    }

    const editDocument = () => {
      router.push(`/knowledge/space/${spaceId.value}/document/${documentId.value}/edit`)
    }



    const copySource = () => {
      navigator.clipboard.writeText(documentContent.value).then(() => {
        ElMessage.success('源码已复制到剪贴板')
      }).catch(() => {
        ElMessage.error('复制失败')
      })
    }

    const toggleFullscreen = () => {
      isFullscreen.value = !isFullscreen.value
      if (isFullscreen.value) {
        document.documentElement.requestFullscreen()
      } else {
        document.exitFullscreen()
      }
    }

    const closePreview = () => {
      if (window.opener) {
        window.close()
      } else {
        router.back()
      }
    }

    const scrollToHeading = (headingId) => {
      const element = document.getElementById(headingId)
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' })
      }
    }

    const showVersionHistoryDialog = async () => {
      await loadVersionHistory()
      showVersionHistory.value = true
    }

    const loadVersionHistory = async () => {
      try {
        const response = await documentApi.getDocumentVersions(
          documentId.value,
          getCurrentUser()
        )
        versionHistory.value = response.data
      } catch (error) {
        ElMessage.error('加载版本历史失败: ' + error.message)
      }
    }

    const initVditorPreview = () => {
      const previewElement = document.getElementById('vditor-preview')
      console.log('初始化Vditor预览 - 元素:', previewElement, '内容长度:', documentContent.value?.length)
      if (previewElement && documentContent.value) {
        // 清空之前的内容
        previewElement.innerHTML = ''

        // 使用Vditor的预览功能，优化配置
        Vditor.preview(previewElement, documentContent.value, {
          mode: 'light',
          anchor: 1,
          lineNumber: false,
          math: {
            inlineDigit: true,
            engine: 'KaTeX'
          },
          hljs: {
            style: 'github',
            lineNumber: false
          },
          markdown: {
            toc: true,
            autoSpace: true,
            fixTermTypo: true,
            chinesePunct: true
          }
        })
      }
    }

    const initVditorTextPreview = () => {
      const previewElement = document.getElementById('vditor-text-preview')
      if (previewElement && documentContent.value) {
        // 清空之前的内容
        previewElement.innerHTML = ''

        // 将文本内容包装为代码块进行预览
        const textAsMarkdown = '```\n' + documentContent.value + '\n```'

        // 使用Vditor的预览功能
        Vditor.preview(previewElement, textAsMarkdown, {
          mode: 'light',
          anchor: 0,
          lineNumber: true,
          hljs: {
            style: 'github',
            lineNumber: true
          }
        })
      }
    }

    const loadWordDocument = async () => {
      try {
        // 构建Word文档下载URL
        const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9090'
        const currentUser = getCurrentUser()
        if (!currentUser) {
          ElMessage.error('无法获取当前用户信息，请重新登录')
          return
        }
        const fileUrl = `${baseUrl}/api/documents/${documentId.value}/file?username=${encodeURIComponent(currentUser)}`

        // 获取Word文档的二进制内容
        const response = await fetch(fileUrl)
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const arrayBuffer = await response.arrayBuffer()

        // 使用Mammoth转换为HTML
        const result = await mammoth.convertToHtml({ arrayBuffer })
        wordHtmlContent.value = result.value

        // 如果有警告信息，可以在控制台输出
        if (result.messages && result.messages.length > 0) {
          console.warn('Word转换警告:', result.messages)
        }
      } catch (error) {
        console.error('加载Word文档失败:', error)
        wordHtmlContent.value = '<p>Word文档加载失败，请尝试下载查看</p>'
      }
    }

    const loadPdfDocument = async () => {
      try {
        // 构建PDF预览URL，使用文件下载接口
        const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9090'
        const currentUser = getCurrentUser()
        if (!currentUser) {
          ElMessage.error('无法获取当前用户信息，请重新登录')
          return
        }
        pdfUrl.value = `${baseUrl}/api/documents/${documentId.value}/file?username=${encodeURIComponent(currentUser)}`
      } catch (error) {
        console.error('加载PDF文档失败:', error)
        ElMessage.error('PDF文档加载失败')
      }
    }

    const previewVersion = (version) => {
      ElMessage.info(`预览版本 v${version.versionNumber}`)
      // 实现版本预览逻辑
    }

    const restoreVersion = async (version) => {
      try {
        await ElMessageBox.confirm(
          `确定要恢复到版本 v${version.versionNumber} 吗？`,
          '确认恢复',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 实现版本恢复逻辑
        ElMessage.success('版本恢复成功')
        showVersionHistory.value = false
        await loadDocument()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('版本恢复失败: ' + error.message)
        }
      }
    }

    const getTypeLabel = (type) => {
      const typeMap = {
        markdown: 'Markdown',
        text: '文本',
        docx: 'Word',
        pdf: 'PDF'
      }
      return typeMap[type] || type
    }

    const getTypeTagType = (type) => {
      const typeMap = {
        markdown: 'primary',
        text: 'success',
        docx: 'warning',
        pdf: 'danger'
      }
      return typeMap[type] || ''
    }

    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    }

    // 键盘快捷键
    const handleKeydown = (event) => {
      if (event.ctrlKey || event.metaKey) {
        switch (event.key) {
          case 's':
            event.preventDefault()
            editDocument()
            break
          case 'd':
            event.preventDefault()
            downloadDocument()
            break
          case 'f':
            event.preventDefault()
            toggleFullscreen()
            break
        }
      }
      if (event.key === 'Escape' && isFullscreen.value) {
        toggleFullscreen()
      }
    }

    // 监听路由参数变化
    watch(
      () => route.params.documentId,
      (newDocumentId) => {
        console.log('路由参数变化，documentId:', newDocumentId)
        if (newDocumentId && newDocumentId !== 'undefined') {
          loadDocument()
        }
      },
      { immediate: true }
    )

    // 监听视图模式变化
    watch(
      () => viewMode.value,
      async (newMode, oldMode) => {
        console.log('视图模式切换:', oldMode, '->', newMode)
        if (newMode === 'preview' && documentInfo.value) {
          // 切换到预览模式时，重新初始化预览组件
          await nextTick()
          const docType = documentInfo.value?.documentType?.toLowerCase()
          const fileExt = documentInfo.value?.fileExtension?.toLowerCase()

          if (docType === 'markdown' || fileExt === 'md') {
            initVditorPreview()
          } else if (docType === 'text' || fileExt === 'txt') {
            initVditorTextPreview()
          }
        } else if (newMode === 'source') {
          // 切换到源码模式时，确保有内容显示
          if (!documentContent.value && documentInfo.value?.content) {
            documentContent.value = documentInfo.value.content
          }
        }
      }
    )

    // 生命周期
    onMounted(() => {
      console.log('组件挂载，documentId:', documentId.value)
      // 如果路由参数已经存在，立即加载
      if (documentId.value && documentId.value !== 'undefined') {
        loadDocument()
      }
      document.addEventListener('keydown', handleKeydown)
    })

    onUnmounted(() => {
      document.removeEventListener('keydown', handleKeydown)
    })

    return {
      documentInfo,
      documentContent,
      markdownHtml,
      wordHtmlContent,
      pdfUrl,
      tocItems,
      versionHistory,
      loading,
      error,
      viewMode,
      isFullscreen,
      showToc,
      showVersionHistory,
      isFavorite,
      spaceId,
      spaceName,
      loadDocument,
      initVditorPreview,
      initVditorTextPreview,
      loadWordDocument,
      loadPdfDocument,
      toggleFavorite,
      downloadDocument,
      editDocument,
      copySource,
      toggleFullscreen,
      closePreview,
      scrollToHeading,
      showVersionHistoryDialog,
      previewVersion,
      restoreVersion,
      getTypeLabel,
      getTypeTagType,
      formatDate,
      canEdit,
      canEditTooltip
    }
  }
}
</script>

<style scoped>
.document-preview-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.document-info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
}

.doc-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.title-icon {
  font-size: 24px;
  color: #409eff;
}

.doc-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.doc-meta {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.info-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.preview-content.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: white;
}

.loading-container,
.error-container {
  flex: 1;
  padding: 40px;
}

.preview-mode,
.source-mode {
  flex: 1;
  overflow: auto;
  background: white;
}

.markdown-preview {
  padding: 40px;
  max-width: 900px;
  margin: 0 auto;
}

.markdown-content {
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3),
.markdown-content :deep(h4),
.markdown-content :deep(h5),
.markdown-content :deep(h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content :deep(h1) {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.markdown-content :deep(h2) {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.markdown-content :deep(p) {
  margin-bottom: 16px;
}

.markdown-content :deep(code) {
  background: #f6f8fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 85%;
}

.markdown-content :deep(pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin-bottom: 16px;
}

.text-preview {
  padding: 40px;
}

.text-content {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.word-preview {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.word-content {
  font-family: 'Times New Roman', serif;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.word-content :deep(p) {
  margin-bottom: 12px;
}

.word-content :deep(h1),
.word-content :deep(h2),
.word-content :deep(h3),
.word-content :deep(h4),
.word-content :deep(h5),
.word-content :deep(h6) {
  margin-top: 20px;
  margin-bottom: 12px;
  font-weight: bold;
}

.word-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

.word-content :deep(td),
.word-content :deep(th) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.loading-word,
.loading-pdf {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-word span,
.loading-pdf span {
  margin-top: 12px;
  font-size: 14px;
}

.pdf-preview {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pdf-iframe {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

.file-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.source-mode {
  padding: 20px;
}

.source-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.file-info {
  font-size: 14px;
  color: #606266;
}

.source-content {
  background: #f6f8fa;
  padding: 20px;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

.toc-sidebar {
  width: 280px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.toc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.toc-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.toc-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.toc-item {
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.4;
  transition: background-color 0.3s;
}

.toc-item:hover {
  background-color: #f0f9ff;
}

.toc-level-1 {
  font-weight: 600;
}

.toc-level-2 {
  padding-left: 24px;
}

.toc-level-3 {
  padding-left: 36px;
  font-size: 13px;
}

.toc-level-4,
.toc-level-5,
.toc-level-6 {
  padding-left: 48px;
  font-size: 12px;
  color: #909399;
}

.version-history {
  max-height: 500px;
  overflow-y: auto;
}

.version-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.version-number {
  font-weight: 600;
  color: #409eff;
}

.version-author {
  color: #606266;
  font-size: 14px;
}

.version-actions {
  display: flex;
  gap: 8px;
}

.version-summary {
  font-size: 14px;
  color: #606266;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .document-info-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .doc-meta {
    gap: 12px;
  }

  .toc-sidebar {
    display: none;
  }

  .markdown-preview {
    padding: 20px;
  }
}
</style>